import os
from os import listdir
from os.path import isfile, join
import urllib
import urllib2

import httplib
import mimetypes
import MultipartPostHandler


def init(ptr_current_oper):
    """
    Where everything begins
    """
    #ptr_current_oper = 'salida/'
    print "-----------------------------------------------"
    print "      starting loading sequence   "
    print "-----------------------------------------------"
    
    
    # get all lats
    latpath =  os.path.abspath( ptr_current_oper )   
    
    onlyfiles = [ f for f in listdir(latpath) if isfile(join(latpath,f)) ]
    
    int_file_cntr = 0
    
    # prep the post
    base_values = ( ('resolution','0.25'),
                    ('type',ptr_current_oper), )
    
    str_host = 'http://rel01dev05.innova-t.appspot.com'
    str_selector = '/marovi/processMasterFile/'
    
    for latfile in onlyfiles:
        int_file_cntr += 1
        print "file: %d %s"  % (int_file_cntr, latfile)
        # process each file
        # we send each file
        
        filepath = ptr_current_oper +'/' + latfile
        
        params = { 'masterFile' : file(filepath, 'rb'), 'resolution':'0.25', 
                  'type':ptr_current_oper  }
        opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
        str_resp = opener.open(str_host + str_selector, params).read()
        print str_resp

    
    if ptr_current_oper == 'lng':
        return
    else:
        print "now we go for the longitude"
        init('lng')
    
    print "-----------------------------------------------"
    print "           the end"
    print "-----------------------------------------------"        

if __name__ == '__main__':
    init('lat')